package com.fjh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fjh.dao.ProEsDao;
import com.fjh.domain.Prod;
import com.fjh.domain.User;
import com.fjh.es.ProdEs;
import com.fjh.feign.ProdCommMemberFeign;
import com.fjh.mapper.ProdMapper;
import com.fjh.model.ProdCommVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjh.domain.ProdComm;
import com.fjh.mapper.ProdCommMapper;
import com.fjh.service.ProdCommService;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

@Service
@Slf4j
public class ProdCommServiceImpl extends ServiceImpl<ProdCommMapper, ProdComm> implements ProdCommService{
    @Autowired
    private ProdMapper prodMapper;
    @Autowired
    private ProdCommMapper prodCommMapper;

    @Autowired
    private ProEsDao proEsDao;

    @Autowired
    private ProdCommMemberFeign prodCommMemberFeign;

    @Override
    public Page<ProdComm> loadProdCommPage(Page<ProdComm> page, ProdComm prodComm) {
        //先判断是否有名字传入
        String prodName = prodComm.getProdName();
        List<Long> prodIds = null;
        if (StringUtils.hasText(prodName)){
            //查询商品表
            List<Prod> prods = prodMapper.selectList(new LambdaQueryWrapper<Prod>()
                    .like(Prod::getProdName, prodName)
            );
            if (!CollectionUtils.isEmpty(prods)){
                //拿到prodIds
                        prodIds = prods.stream()
                        .map(Prod::getProdId)
                        .collect(Collectors.toList());
            }else {
                //没查到，直接返回
                page.setRecords(Collections.emptyList());
                page.setTotal(0L);
                return page;
            }
        }
        //分页查询评论表
        Page<ProdComm> prodCommPage = prodCommMapper.selectPage(page, new LambdaQueryWrapper<ProdComm>()
                .eq(!ObjectUtils.isEmpty(prodComm.getStatus()), ProdComm::getStatus, prodComm.getStatus())
                .in(!CollectionUtils.isEmpty(prodIds), ProdComm::getProdId, prodIds)
                .orderByDesc(ProdComm::getRecTime)
        );
        //组装名字
        List<ProdComm> prodComms = prodCommPage.getRecords();
        if (!CollectionUtils.isEmpty(prodComms)){
            //说明数据库里还没有评论
            return prodCommPage;
        }
        //现在开始精确查询
        //根据查询到的评论反向查询商品ids
        List<Long> finalProdIds = prodComms.stream()
                .map(ProdComm::getProdId)
                .collect(Collectors.toList());
        // 再来查询商品表 因为我不确定上面是否传入了商品名字  我也不能全查询商品（1千万条）或者评论（千万级别的评论）
        List<Prod> prods = prodMapper.selectBatchIds(finalProdIds);
        //组装
        //循环评论  过滤出商品id相同的商品，设置名字
        prodComms.forEach(prodComm1 -> {
            Prod prod1 = prods.stream()
                    .filter(prod -> prod.getProdId().equals(prodComm1.getProdCommId()))
                    .collect(Collectors.toList())
                    .get(0);
            prodComm1.setProdName(prod1.getProdName());
        });
        return prodCommPage;
    }

    /**
     * 根据用商品id查询评论总览
     * @param prodId
     * @return
     */
    @Override
    public ProdCommVo findFrontProdComm(Long prodId) {
        //获得好评率  获得好评数
        ProdEs prodEs = proEsDao.findById(prodId).get();
        BigDecimal positiveRating = prodEs.getPositiveRating();
        Long praiseNumber = prodEs.getPraiseNumber();
        //总评数
        // 前台不建议一下吧某个商品的数据全查到  因为评论数量特别大 可以发多个小的sql语句
        Integer allProdComm = prodCommMapper.selectCount(new LambdaQueryWrapper<ProdComm>()
                .eq(ProdComm::getProdId, prodId)
                .eq(ProdComm::getStatus, 1)
        );
        // 中评
        Integer secondProdComm = prodCommMapper.selectCount(new LambdaQueryWrapper<ProdComm>()
                .eq(ProdComm::getProdId, prodId)
                .eq(ProdComm::getStatus, 1)
                .eq(ProdComm::getEvaluate, 1)
        );
        // 差评
        Integer badProdComm = prodCommMapper.selectCount(new LambdaQueryWrapper<ProdComm>()
                .eq(ProdComm::getProdId, prodId)
                .eq(ProdComm::getStatus, 1)
                .eq(ProdComm::getEvaluate, 2)
        );
        // 有图
        Integer picProdComm = prodCommMapper.selectCount(new LambdaQueryWrapper<ProdComm>()
                .eq(ProdComm::getProdId, prodId)
                .eq(ProdComm::getStatus, 1)
                .isNotNull(ProdComm::getPics)
        );
        return ProdCommVo.builder()
                .praiseNumber(Integer.valueOf(praiseNumber.toString()))
                .positiveRating(positiveRating)
                .number(allProdComm)
                .picNumber(picProdComm)
                .negativeNumber(badProdComm)
                .secondaryNumber(secondProdComm)
                .build();
    }

    /**
     * 分页查询单个商品的评论  代码要写步骤的注释
     * 1.查询评论表
     * 2.获取用户的id
     * 3.远程调用会员模块 拿到用户的头像和昵称
     * 4.可能涉及到脱敏
     * 5.组装数据 返回
     * @param prodId
     * @param page
     * @param evaluate
     * @return
     */
    @Override
    public Page<ProdComm> prodCommPageByProd(Long prodId, Page<ProdComm> page, Integer evaluate) {
        Page<ProdComm> prodCommPage = prodCommMapper.selectPage(page,new LambdaQueryWrapper<ProdComm>()
                .eq(ProdComm::getProdId,prodId)
                .eq(evaluate != null && evaluate != -1, ProdComm::getEvaluate, evaluate)
                .orderByDesc(ProdComm::getScore,ProdComm::getRecTime)
        );
        List<ProdComm> prodCommList = prodCommPage.getRecords();
        if (CollectionUtils.isEmpty(prodCommList)){
            return prodCommPage;
        }
        //用户的昵称和头像没有
        List<String> userIds = prodCommList.stream()
                .map(ProdComm::getUserId)
                .collect(Collectors.toList());
        List<User> userList = prodCommMemberFeign.getUserListByIds(userIds);
        if (!CollectionUtils.isEmpty(userList)){
            //组装数据
            prodCommList.forEach(prodComm -> {
               //过滤用户的id
                User user1 = userList.stream()
                        .filter(user -> user.getUserId().equals(prodComm.getUserId()))
                        .collect(Collectors.toList())
                        .get(0);
                //脱敏
                String nickName = user1.getNickName();
                if (nickName.length()>=11){
                    StringBuilder stringBuilder = new StringBuilder(nickName);
                    StringBuilder replace = stringBuilder.replace(0, 10, "**********");
                    prodComm.setNickName(replace.toString());
                }
                prodComm.setPic(user1.getPic());
            });
        }
        return prodCommPage;
    }
}
